import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, Select, Space, Tag, Modal, message, Popconfirm, DatePicker } from 'antd';
import { SearchOutlined, ReloadOutlined, EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { request } from 'umi';
import { getAllCleaners, createCleaner, updateCleaner, deleteCleaner } from '../../../services/cleaning';
import { getStores } from '../../../services/store';
import moment from 'moment';

const { Option } = Select;

const CleanerList = () => {
  const [cleaners, setCleaners] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [cleanerForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  const [searchParams, setSearchParams] = useState({});
  const [formVisible, setFormVisible] = useState(false);
  const [currentCleaner, setCurrentCleaner] = useState(null);
  const [formTitle, setFormTitle] = useState('创建保洁员');
  const [stores, setStores] = useState([]);

  const fetchCleaners = async () => {
    try {
      setLoading(true);
      const params = {
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      };
      const res = await getAllCleaners(params);
      if (res.success) {
        setCleaners(res.data.list || []);
        setPagination({
          ...pagination,
          total: res.data.total || 0,
        });
      } else {
        message.error(res.message || '获取保洁员列表失败');
      }
    } catch (error) {
      message.error('获取保洁员列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCleaners();
    fetchStores();
  }, [pagination.current, pagination.pageSize, searchParams]);

  const fetchStores = async () => {
    try {
      const res = await getStores({ page_size: 999 });
      if (res.success) {
        setStores(res.data.list || []);
      } else {
        message.error('获取门店列表失败');
      }
    } catch (error) {
      message.error('获取门店列表失败');
    }
  };

  const handleAdd = () => {
    setFormTitle('创建保洁员');
    setCurrentCleaner(null);
    cleanerForm.resetFields();
    setFormVisible(true);
  };

  const handleEdit = (record) => {
    setFormTitle('编辑保洁员');
    setCurrentCleaner(record);
    let store_ids = [];
    if (record.store_ids) {
      try {
        if (typeof record.store_ids === 'string') {
          store_ids = JSON.parse(record.store_ids);
        } else {
          store_ids = record.store_ids;
        }
      } catch (e) {
        console.error('Failed to parse store_ids', record.store_ids, e);
        store_ids = [];
      }
    }

    cleanerForm.setFieldsValue({
      ...record,
      entry_date: record.entry_date ? moment.unix(record.entry_date) : null,
      store_ids: Array.isArray(store_ids) ? store_ids : [],
    });
    setFormVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      setLoading(true);
      const res = await deleteCleaner(id);
      if (res.success) {
        message.success('删除成功');
        fetchCleaners();
      } else {
        message.error(res.message || '删除失败');
      }
    } catch (error) {
      message.error('删除失败');
    } finally {
      setLoading(false);
    }
  };

  const handleFormSubmit = async () => {
    try {
      const values = await cleanerForm.validateFields();
      setLoading(true);

      let res;
      const submitValues = {
        ...values,
        entry_date: values.entry_date ? values.entry_date.unix() : 0,
        store_ids: JSON.stringify(values.store_ids || [])
      }

      if (currentCleaner) {
        res = await updateCleaner(currentCleaner.id, submitValues);
      } else {
        res = await createCleaner(submitValues);
      }

      if (res.success) {
        message.success(`${currentCleaner ? '更新' : '创建'}成功`);
        setFormVisible(false);
        fetchCleaners();
      } else {
        message.error(res.message || `${currentCleaner ? '更新' : '创建'}失败`);
      }
    } catch (error) {
      message.error('表单提交失败');
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    { title: '姓名', dataIndex: 'name', key: 'name' },
    { title: '联系电话', dataIndex: 'phone', key: 'phone' },
    {
      title: '所属门店',
      dataIndex: 'store_ids',
      key: 'store_ids',
      render: (text) => {
        let storeIds = [];
        if (text) {
          try {
            if (typeof text === 'string') {
              storeIds = JSON.parse(text);
            } else {
              storeIds = text;
            }
          } catch (e) {
            console.error('Failed to parse store_ids in render', text, e);
            storeIds = [];
          }
        }
        if (!Array.isArray(storeIds)) {
          return '';
        }
        return storeIds.map((id) => stores.find((s) => s.id === id)?.name || id).join(', ');
      },
    },
    {
      title: '入职日期',
      dataIndex: 'entry_date',
      key: 'entry_date',
      render: (text) => text ? moment.unix(text).format('YYYY-MM-DD') : ''
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '可用' : '不可用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)}>编辑</Button>
          <Popconfirm title="确定删除吗？" onConfirm={() => handleDelete(record.id)}>
            <Button type="link" icon={<DeleteOutlined />} danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleSearch = (values) => {
    setSearchParams(values);
    setPagination({ ...pagination, current: 1 });
  };

  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    setPagination({ ...pagination, current: 1 });
  };

  return (
    <PageContainer>
      <Card>
        <Form form={form} layout="inline" onFinish={handleSearch} style={{ marginBottom: 24 }}>
          <Form.Item name="name" label="姓名">
            <Input placeholder="请输入姓名" allowClear />
          </Form.Item>
          <Form.Item name="phone" label="联系电话">
            <Input placeholder="请输入联系电话" allowClear />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" style={{ width: 150 }} allowClear>
              <Option value={1}>可用</Option>
              <Option value={0}>不可用</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>搜索</Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>创建保洁员</Button>
        </div>
        <Table
          columns={columns}
          dataSource={cleaners}
          pagination={pagination}
          loading={loading}
          onChange={(p) => setPagination(p)}
          rowKey="id"
        />
      </Card>
      <Modal
        title={formTitle}
        visible={formVisible}
        onCancel={() => setFormVisible(false)}
        onOk={handleFormSubmit}
        destroyOnClose
      >
        <Form form={cleanerForm} layout="vertical">
          <Form.Item label="姓名" name="name" rules={[{ required: true, message: '请输入姓名' }]}>
            <Input />
          </Form.Item>
          <Form.Item label="联系电话" name="phone" rules={[{ required: true, message: '请输入联系电话' }]}>
            <Input />
          </Form.Item>
          <Form.Item label="所属门店" name="store_ids" rules={[{ required: true, message: '请选择所属门店' }]}>
            <Select mode="multiple" placeholder="请选择门店">
              {stores.map(store => (
                <Option key={store.id} value={store.id}>{store.name}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="入职日期" name="entry_date" rules={[{ required: true, message: '请选择入职日期' }]}>
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="状态" name="status" rules={[{ required: true }]}>
            <Select>
              <Option value={1}>可用</Option>
              <Option value={0}>不可用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default CleanerList;